package com.hui.auth.config.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.jcache.config.JCacheConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Redis配置
 *
 * @author 廖云辉
 * @apiNote <p>
 * <artifactId>spring-data-redis</artifactId>提供了如下功能：
 * 1. 连接池自动管理，提供了一个高度封装的“RedisTemplate”类
 * 2. 针对jedis客户端中大量api进行了归类封装,将同一类型操作封装为operation接口
 * ValueOperations：简单K-V操作
 * SetOperations：set类型数据操作
 * ZSetOperations：zset类型数据操作
 * HashOperations：针对map类型的数据操作
 * ListOperations：针对list类型的数据操作
 * 3. 提供了对key的“bound”(绑定)便捷化操作API，可以通过bound封装指定的key，然后进行一系列的操作而无须“显式”的再次指定Key，即BoundKeyOperations：
 * BoundValueOperations
 * BoundSetOperations
 * BoundListOperations
 * BoundSetOperations
 * BoundHashOperations
 * 4. 将事务操作封装， 由容器控制。
 * 5. 针对数据的“序列化/反序列化”，提供了多种可选择策略(RedisSerializer)
 * 6. 基于设计模式，和JMS开发思路，将pub/sub的API设计进行了封装，使开发更加便捷。
 * 7.spring-data-redis中，并没有对sharding提供良好的封装，如果你的架构是基于sharding，那么你需要自己去实现，这也是sdr和jedis相比，唯一缺少的特性。
 */
@Configuration
@EnableCaching
public class RedisConfig extends JCacheConfigurerSupport {
    @Value("${spring.redis.pool.test-on-borrow:true}")
    private boolean testOnBorrow;
    @Value("${spring.redis.pool.test-on-create:false}")
    private boolean testOnCreate;
    @Value("${spring.redis.pool.test-on-return:false}")
    private boolean testOnReturn;
    @Value("${spring.redis.pool.test-while-idle:true}")
    private boolean testWhileIdle;
    @Value("${spring.redis.pool.use-pool:true}")
    private boolean usePool;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.database}")
    private int database;

    //    @Autowired
//    private JedisConnectionFactory jedisConnectionFactory;//自动注入不可控
    @Bean
    JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
        connectionFactory.setHostName(host);
        connectionFactory.setPort(port);
        connectionFactory.setPassword(password);
        connectionFactory.setDatabase(database);
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setTestOnBorrow(testOnBorrow);
        jedisPoolConfig.setTestOnCreate(testOnCreate);
        jedisPoolConfig.setTestOnReturn(testOnReturn);
        jedisPoolConfig.setTestWhileIdle(testWhileIdle);
        jedisPoolConfig.setMinIdle(0);
        jedisPoolConfig.setMaxTotal(3);
        jedisPoolConfig.setMaxWaitMillis(10000);
        connectionFactory.setPoolConfig(jedisPoolConfig);
        connectionFactory.setUsePool(true);
        return connectionFactory;
    }

    //    @PostConstruct
//    public void init() {
//        JedisPoolConfig jedisPoolConfig = jedisConnectionFactory.getPoolConfig();
//        jedisPoolConfig.setTestOnBorrow(testOnBorrow);
//        jedisPoolConfig.setTestOnCreate(testOnCreate);
//        jedisPoolConfig.setTestOnReturn(testOnReturn);
//        jedisPoolConfig.setTestWhileIdle(testWhileIdle);
//        jedisConnectionFactory.setPoolConfig(jedisPoolConfig);
//        jedisConnectionFactory.setUsePool(usePool);
//        jedisConnectionFactory.setPassword(password);
//    }
    @Bean
    public KeyGenerator wiselyKeyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object param : params) {
                sb.append(param.toString());
            }
            return sb.toString();
        };
    }

//    @Bean
//    @Primary
//    /*反序列化出问题*/
//    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
//        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(factory);
//        ObjectMapper om = new ObjectMapper();
//        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(om);
//        stringRedisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
//        stringRedisTemplate.afterPropertiesSet();
//        return stringRedisTemplate;
//    }

//    @Bean
//    @Primary
     /*反序列化出问题*/
//    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
//        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(factory);
//        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
//        ObjectMapper om = new ObjectMapper();
//        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
////        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
//        jackson2JsonRedisSerializer.setObjectMapper(om);
//        stringRedisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
//        stringRedisTemplate.afterPropertiesSet();
//        return stringRedisTemplate;
//    }


    /*jdk序列化，可用*/
//    @Bean
//    @Primary
//    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
//        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(factory);
//        stringRedisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
//        stringRedisTemplate.afterPropertiesSet();
//        return stringRedisTemplate;
//    }

    /*可用*/
    @Bean
    @Primary
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(factory);
        stringRedisTemplate.setValueSerializer(new RedisObjectSerializer());
        stringRedisTemplate.afterPropertiesSet();
        return stringRedisTemplate;
    }

    @Bean
    public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        return new RedisCacheManager(redisTemplate);
    }

}